﻿// 
// Created By: Xiaofeng.Gu 2021/03/18
// 

#include "EventHandlerClientNodeConnection.hpp"
#include "CybertronTaskRunnerPoolServer.hpp"
#include "cybertron/core/UtilStateHelper.hpp"
EventHandlerClientNodeConnection::EventHandlerClientNodeConnection(CybertronTaskRunnerPoolServer* pServer)
{
	mbReg = false;
	mpServer = pServer;
	mMessageRouter.registerHandler(
		Common::ESimOneKeepAlive,
		[this](Message& msg) {
		onHandleNodeHeartbeatMessage(msg);
	});
	mMessageRouter.registerHandler(
		TaskRunnerPool::ETaskRunnerPoolRegisterReq,
		[this](Message& msg) {
		onHandleNodeRegisterRequestMessage(msg);
	});
	mMessageRouter.registerHandler(
		TaskRunnerPool::ETaskRunnerPoolReportStateReq,
		[this](Message& msg) {
		onHandleNodeStateMessage(msg);
	});

}

EventHandlerClientNodeConnection::~EventHandlerClientNodeConnection()
{
}

void EventHandlerClientNodeConnection::onDisconnected()
{
	mpServer->OnDisConnectClient(getSocket(), &mNodeInfo);
}

void EventHandlerClientNodeConnection::onHandleNodeHeartbeatMessage(Message& msg)
{
	Common::SimOneKeepAlive alive;
	if (!msg.toProtobuf(alive))
	{
		return;
	}

	int timestamp = alive.timestamp();
	Common::SimOneKeepAliveRet aliveRet;
	aliveRet.set_timestamp(timestamp);
	auto pSocket = getSocket();

	pSocket->send(Common::ESimOneKeepAliveRet, aliveRet);
}

void EventHandlerClientNodeConnection::onHandleNodeRegisterRequestMessage(Message& msg)
{
	TaskRunnerPool::TaskRunnerPoolRegisterReq registerRequest;
	if (!msg.toProtobuf(registerRequest))
	{
		return;
	}
	
	std::string id = registerRequest.nodeid();
	Common::EWorkNodeType worktype = registerRequest.worktype();
	std::string groupId = registerRequest.groupid();
	string type = UtilStateHelper::getWorkNodeTypeName(worktype);
	
	mNodeInfo.groupId = groupId;
	mNodeInfo.id = id;
	mNodeInfo.type = type;
	mNodeInfo.description = registerRequest.description();
	mNodeInfo.userData = registerRequest.userdata();
	mNodeInfo.tag = registerRequest.tag();

	mpServer->queueControlCommand(getSocket(), msg);
	mbReg = true;
}
void EventHandlerClientNodeConnection::onHandleNodeStateMessage(Message& msg) {
	mpServer->queueControlCommand(getSocket(), msg);
}

void EventHandlerClientNodeConnection::onMessage(Message& msg) {
	mMessageRouter.onMessage(msg);
}
